package com.aaa.service.impl;

import com.aaa.entity.OvertimeApplication;
import com.aaa.entity.Result;
import com.aaa.mapper.ApplicationMapper;
import com.aaa.service.ApplicationService;
import com.aaa.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 残業申請服务实现类
 */
@Service
public class ApplicationServiceImpl implements ApplicationService {
    // 依赖注入
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result<OvertimeApplication> submitApplication(OvertimeApplication overtimeApplication) {
        try {
            // 1. 基本参数校验
            if (overtimeApplication.getStartTime() == null || overtimeApplication.getEndTime() == null) {
                return Result.paramError("开始时间和结束时间是必填项。");
            }
            if (overtimeApplication.getStartTime().after(overtimeApplication.getEndTime())) {
                return Result.paramError("开始时间必须在结束时间之前。");
            }

            // 2. 从请求头中获取并验证Token
            String token = TokenUtil.extractToken(request);
            if (token == null) {
                return Result.unauthorized("没有认证令牌。");
            }

            // 3. 解析Token获取用户信息
            Map<String, Object> claims = TokenUtil.parseToken(token);
            if (claims == null) {
                return Result.unauthorized("这是无效的令牌。");
            }

            // 4. 获取当前用户ID
            Integer userId = (Integer) claims.get("userId");
            if (userId == null) {
                return Result.unauthorized("用户信息不正确。");
            }

            // 5. 设置申请信息
            overtimeApplication.setUserId(userId);          // 设置申请人ID
            overtimeApplication.setInitiatorId(userId);    // 设置发起人ID
            overtimeApplication.setStatus("pending");      // 设置默认状态为审批中

            // 6. 保存申请到数据库
            int affectedRows = applicationMapper.insert(overtimeApplication);
            if (affectedRows == 0) {
                return Result.businessError("加班申请保存失败。");
            }

            // 7. 返回成功响应
            return Result.success(overtimeApplication);

        } catch (Exception e) {
            // 8. 处理系统异常
            return Result.internalError("系统错误: " + e.getMessage());
        }
    }
}